package com.otitan.la.forest.industry.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.industry.constant.DicTypeEnum;
import com.otitan.la.forest.industry.mapper.SupplyMarketMapper;
import com.otitan.la.forest.industry.entity.SupplyMarketEntity;
import com.otitan.la.forest.industry.dto.SupplyMarketDTO;
import com.otitan.la.forest.industry.utils.CommonUtils;
import com.otitan.la.forest.industry.vo.SupplyMarketVO;
import com.otitan.la.forest.industry.service.SupplyMarketService;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SupplyMarketServiceImpl extends ServiceImpl<SupplyMarketMapper, SupplyMarketEntity> implements SupplyMarketService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${redis.key-prefix}")
    private String redisKeyPrefix;


    @Override
    public DataResult add(SupplyMarketEntity supplyMarket, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<SupplyMarketEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SupplyMarketEntity::getEnterpriseName, supplyMarket.getEnterpriseName());
        int count = this.count(queryWrapper);
        if (count > 0){
            return DataResult.fail("企业名称不能重复");
        }
        boolean isSuccess = this.save(supplyMarket);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        boolean isSuccess = this.removeByIds(ids);
        log.debug("\n>>>>>>>>> 【删除供销服务】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, ids);
        return DataResult.success();
    }

    @Override
    public DataResult editor(SupplyMarketEntity supplyMarket, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<SupplyMarketEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SupplyMarketEntity::getEnterpriseName, supplyMarket.getEnterpriseName());
        queryWrapper.ne(SupplyMarketEntity::getId, supplyMarket.getId());
        int count = this.count(queryWrapper);
        if (count > 0){
            return DataResult.fail("企业名称不能重复");
        }

        boolean isSuccess = this.updateById(supplyMarket);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult findPageData(long page, long size, SupplyMarketDTO supplyMarket) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<SupplyMarketEntity> queryWrapper = Wrappers.lambdaQuery();

        // 企业名称
        if (StrUtil.isNotEmpty(supplyMarket.getEnterpriseName())){
            queryWrapper.like(SupplyMarketEntity::getEnterpriseName, supplyMarket.getEnterpriseName());
        }
        // 类别
        if (StrUtil.isNotEmpty(supplyMarket.getType())){
            queryWrapper.eq(SupplyMarketEntity::getType, supplyMarket.getType());
        }
        // 交易类型
        if (StrUtil.isNotEmpty(supplyMarket.getTransactionType())){
            queryWrapper.eq(SupplyMarketEntity::getTransactionType, supplyMarket.getTransactionType());
        }

        IPage<SupplyMarketEntity> iPage = this.page(pagePlug, queryWrapper);

        IPage<SupplyMarketVO> iPageVO = new Page<>();
        BeanUtils.copyProperties(iPage, iPageVO);

        List<SupplyMarketVO> listVO = new ArrayList<>();
        // 转换使用字典的属性
        if (CollUtil.isNotEmpty(iPage.getRecords())) {
            iPage.getRecords().forEach(item -> {
                SupplyMarketVO vo = new SupplyMarketVO();
                BeanUtils.copyProperties(item, vo);
                // 需要转换的具体字典属性
                String typeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix,
                        DicTypeEnum.SUPPLY_MARKET_TYPE.getValue(), vo.getType());
                vo.setTypeName(typeName);
                String transactionTypeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix,
                        DicTypeEnum.TRANSACTION_TYPE.getValue(), vo.getTransactionType());
                vo.setTypeName(typeName);
                vo.setTransactionTypeName(transactionTypeName);
                listVO.add(vo);
            });
        }
        iPageVO.setRecords(listVO);

        return DataResult.success(iPageVO);
    }

    @Override
    public DataResult findOne(String id) {
        SupplyMarketEntity entity = this.getById(id);
        SupplyMarketVO vo = new SupplyMarketVO();
        BeanUtils.copyProperties(entity, vo);
        // 需要转换的具体字典属性
        String typeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix,
                DicTypeEnum.SUPPLY_MARKET_TYPE.getValue(), vo.getType());
        vo.setTypeName(typeName);
        String transactionTypeName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix,
                DicTypeEnum.TRANSACTION_TYPE.getValue(), vo.getTransactionType());
        vo.setTypeName(typeName);
        vo.setTransactionTypeName(transactionTypeName);
        return DataResult.success(vo);
    }
}